<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title></title>
  </head>
  <body>
    <div id="app">
      <ul>
        <li><router-link to="/">Home</router-link></li>
        <li><router-link to="/post/1">/post/1</router-link></li>
        <li><router-link to="/post/2">/post/2</router-link></li>
      </ul>
      <router-view></router-view>
    </div>
    <script src="https://unpkg.com/vue@2/dist/vue.js"></script>
    <script src="https://unpkg.com/vue-router@3/dist/vue-router.js"></script>
    <script>
      function getPostById(postId) {
        return new Promise((resolve) => {
          setTimeout(() => {
            resolve({
              title: `标题${postId}`,
              content: `内容${postId}`,
            });
          }, 1000);
        });
      }
      const Home = { template: "<div>Home</div>" };
      const Post = {
        props: ["postId"],
        data: () => ({
          post: null, //文章对象
          loading: false, //是否正在调用接口中
          error: null, //是否调用接口出错了，如果出错了在这里放错误的信息
        }),
        beforeRouteEnter(to, from, next) {
          console.log('beforeRouteEnter');
          next(vm=>vm.fetchPost());
        },
        beforeRouteUpdate(to, from, next) {
          console.log('beforeRouteUpdate');
          next(vm=>vm.fetchPost());
        },
        methods: {
          fetchPost() {
            this.post = this.error = null; //先清空老的值
            this.loading = true; //设置loading为true
            return getPostById(this.postId) //调用接口获取 post数据
              .then((post) => (this.post = post)) //如果成功了，把获取的post数据保存到this.post上
              .catch((error) => (this.error = error)) //如果失败了，把失败的错误对象保存到this.error上
              .finally(() => (this.loading = false)); //不管成功还是失败，都要把loading重置为false
          },
        },
        template: `
        <div>
            <template v-if="loading">
                <p>loading......</p>
            </template>
            <template v-if="error">
                <p>{{error.message}}</p>
            </template>
            <template v-if="post">
                <p>title:{{post.title}}</p>
                <p>content:{{post.content}}</p>
            </template>
        </div>
    `,
      };
      var routes = [
        { path: "/", component: Home },
        { path: "/post/:postId", component: Post, props: true },
      ];
      Vue.use(VueRouter);
      var router = new VueRouter({ routes });
      var vm = new Vue({
        el: "#app",
        router,
      });
      /*  router.afterEach(()=>{

      }); */
    </script>
  </body>
</html>
